package com.quectel.core.module.invoice.service.impl;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.quectel.constant.core.invoice.InvoiceConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.core.module.invoice.dao.InvoiceDao;
import com.quectel.core.module.invoice.dto.InvoiceDto;
import com.quectel.core.module.invoice.dto.InvoiceItemDto;
import com.quectel.core.module.invoice.dto.InvoiceTitleDto;
import com.quectel.core.module.invoice.dto.InvoiceTitleSnapshotDto;
import com.quectel.core.module.invoice.entity.InvoiceEntity;
import com.quectel.core.module.invoice.service.InvoiceItemService;
import com.quectel.core.module.invoice.service.InvoiceService;
import com.quectel.core.module.invoice.service.InvoiceTitleService;
import com.quectel.core.module.invoice.service.InvoiceTitleSnapshotService;
import com.quectel.core.module.parking.dto.ParkingOrderDto;
import com.quectel.core.module.parking.service.ParkingOrderService;
import com.quectel.core.module.parkingcard.dto.ParkingCardOrderDto;
import com.quectel.core.module.parkingcard.service.ParkingCardOrderService;
import com.quectel.core.module.propertybill.dto.PropertyBillDto;
import com.quectel.core.module.propertybill.service.PropertyBillService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/03/31 16:28
 */
@DubboService
public class InvoiceServiceImpl implements InvoiceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(InvoiceService.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> INVOICE_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "INVOICE_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<InvoiceDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(INVOICE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private VillageService villageService;
    @Autowired
    private VillageRoomService villageRoomService;


    @Autowired
    private HouseholdService householdService;

    @Autowired
    private InvoiceDao invoiceDao;

    @Autowired
    private InvoiceItemService invoiceItemService;
    @Autowired
    private InvoiceTitleService invoiceTitleService;
    @Autowired
    private InvoiceTitleSnapshotService invoiceTitleSnapshotService;
    @Autowired
    private PropertyBillService propertyBillService;
    @Autowired
    private ParkingCardOrderService parkingCardOrderService;
    @Autowired
    private ParkingOrderService parkingOrderService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitInvoiceApply(InvoiceDto invoiceDto, List<InvoiceItemDto> commonInvoiceItemDtoList) {
        Long save = this.saveOrUpdate(invoiceDto);
        for (InvoiceItemDto invoiceItemDto : commonInvoiceItemDtoList) {
            invoiceItemDto.setInvoiceId(save);
            invoiceItemService.save(invoiceItemDto);
        }

        LOGGER.debug("开票申请-记录保存成功");

        // 更新不同的订单表的开票状态
        if (invoiceDto.getSourceType().equals(InvoiceConstants.InvoiceItemSourceType.PROPERTY_BILL.getType())) {
            for (InvoiceItemDto invoiceItemDto : commonInvoiceItemDtoList) {
                PropertyBillDto propertyBillDto = new PropertyBillDto();
                propertyBillDto.setId(invoiceItemDto.getSourceId());
                propertyBillDto.setInvoiceStatus(InvoiceConstants.InvoiceStatus.TO_BE_INVOICE.getType());
                propertyBillService.updateById(propertyBillDto);
            }
            LOGGER.debug("开票申请-物业费关联账单开票状态更新成功");
        }
        if (invoiceDto.getSourceType().equals(InvoiceConstants.InvoiceItemSourceType.PARKING_BIll.getType())) {
            for (InvoiceItemDto invoiceItemDto : commonInvoiceItemDtoList) {
                ParkingOrderDto parkingOrderDto = new ParkingOrderDto();
                parkingOrderDto.setId(invoiceItemDto.getSourceId());
                parkingOrderDto.setInvoiceStatus(InvoiceConstants.InvoiceStatus.TO_BE_INVOICE.getType());
                parkingOrderService.updateById(parkingOrderDto);
            }
            LOGGER.debug("开票申请-临停缴费账单开票状态更新成功");
        }
        if (invoiceDto.getSourceType().equals(InvoiceConstants.InvoiceItemSourceType.PARKING_CARD.getType())) {
            for (InvoiceItemDto invoiceItemDto : commonInvoiceItemDtoList) {
                ParkingCardOrderDto parkingCardOrderDto = new ParkingCardOrderDto();
                parkingCardOrderDto.setId(invoiceItemDto.getSourceId());
                parkingCardOrderDto.setInvoiceStatus(InvoiceConstants.InvoiceStatus.TO_BE_INVOICE.getType());
                parkingCardOrderService.updateById(parkingCardOrderDto);
            }
            LOGGER.debug("开票申请-月卡关联账单开票状态更新成功");
        }
    }


    @Override
    public Long saveOrUpdate(InvoiceDto dto) {
        if (dto.getId() == null) {
            dto.setId(save(dto));
        } else {
            updateById(dto);
        }
        invoiceItemService.deleteByInvoiceId(dto.getId());

        if (CollectionUtils.isNotEmpty(dto.getInvoiceItems())) {
            dto.getInvoiceItems().forEach(invoiceItemDto -> invoiceItemDto.setInvoiceId(dto.getId()));
            invoiceItemService.batchSave(dto.getInvoiceItems());
        }

        if (dto.getInvoiceTitle() != null) {
            invoiceTitleSnapshotService.deleteByInvoiceId(dto.getId());
            //保存镜像
            InvoiceTitleSnapshotDto invoiceTitleSnapshotDto = new InvoiceTitleSnapshotDto();
            invoiceTitleSnapshotDto.setInvoiceId(dto.getId());
            invoiceTitleSnapshotDto.setInvoiceTitleJson(JacksonUtils.toJsonString(dto.getInvoiceTitle()));
            invoiceTitleSnapshotService.save(invoiceTitleSnapshotDto);
        }

        return dto.getId();
    }


    @Override
    public InvoiceDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                INVOICE_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public InvoiceDto selectById(Long id) {
        InvoiceEntity entity = invoiceDao.selectById(id);
        InvoiceDto invoiceDto = paddingField(CopyUtils.copyObj(entity, InvoiceDto.class));

        if (invoiceDto != null) {
            //镜像
            InvoiceTitleSnapshotDto titleSnapshotDto = invoiceTitleSnapshotService.selectCacheByInvoiceId(invoiceDto.getId());
            if (titleSnapshotDto != null && StringUtils.isNotBlank(titleSnapshotDto.getInvoiceTitleJson())) {
                invoiceDto.setInvoiceTitle(JacksonUtils.parse(titleSnapshotDto.getInvoiceTitleJson(), InvoiceTitleDto.class));
            }
            //申请人
            if (InvoiceConstants.PersonSourceTypeEnum.HOUSEHOLD.getPersonSourceType().equals(invoiceDto.getPersonType())) {
                HouseholdDto householdDto = householdService.selectCacheById(invoiceDto.getPersonId());
                invoiceDto.setPersonName(householdDto != null ? householdDto.getName() : "");
            }
        }

        return invoiceDto;
    }

    @Override
    public List<InvoiceDto> queryList(Map<String, Object> params) {
        List<InvoiceEntity> list = invoiceDao.queryList(params);
        List<InvoiceDto> result = CopyUtils.copyList(list, InvoiceDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private InvoiceDto paddingField(InvoiceDto dto) {
        if (dto != null) {
            VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
            if (villageDto != null) {
                dto.setVillageName(villageDto.getName());
            }

            //查询绑定的items
            List<InvoiceItemDto> invoiceItemDtos = invoiceItemService.selectCacheByInvoiceId(dto.getId());
            dto.setInvoiceItems(invoiceItemDtos);

            //填充抬头名称和类型
            //镜像
            InvoiceTitleSnapshotDto titleSnapshotDto = invoiceTitleSnapshotService.selectCacheByInvoiceId(dto.getId());
            if (titleSnapshotDto != null && StringUtils.isNotBlank(titleSnapshotDto.getInvoiceTitleJson())) {
                InvoiceTitleDto invoiceTitleDto = JacksonUtils.parse(titleSnapshotDto.getInvoiceTitleJson(), InvoiceTitleDto.class);
                if (invoiceTitleDto != null) {
                    dto.setInvoiceTitleName(invoiceTitleDto.getTitle());
                    dto.setInvoiceTitleType(invoiceTitleDto.getType());
                }
            }

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return invoiceDao.queryTotal(params);
    }

    @Override
    public Long save(InvoiceDto dto) {
        InvoiceEntity entity = CopyUtils.copyObj(dto, InvoiceEntity.class);
        entity.setId(Snowflake.nextId());
        invoiceDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(InvoiceDto dto) {
        InvoiceEntity entity = CopyUtils.copyObj(dto, InvoiceEntity.class);

        invoiceDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(InvoiceDto dto) {
        InvoiceEntity entity = CopyUtils.copyObj(dto, InvoiceEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, invoiceDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        invoiceDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
